import pandas as pd
import numpy as np
from .feature_decorator import support_predict

# 保存训练数据的最后几个值用于预测
_last_values = None
_window_size = 3

@support_predict
def prepare_features(df, window_size=3):
    """使用滑动窗口创建历史数据特征"""
    global _last_values, _window_size
    _window_size = window_size
    
    # 确保数据按时间排序
    df = df.copy()
    df['date'] = pd.to_datetime(df.iloc[:, 0])
    df = df.sort_values('date')
    values = df.iloc[:, 1].values
    
    # 如果是训练模式，保存最后几个值
    if len(values) > window_size:
        _last_values = values[-window_size:]
    
    # 创建滑动窗口特征
    X_list = []
    y_list = []
    
    # 如果数据长度小于窗口大小（预测场景）
    if len(values) < window_size:
        if _last_values is not None:
            # 历史数据
            X_list.append(_last_values)
            y_list.append(0)  # 占位
        else:
            # 如果没有历史数据，创建一个全零特征
            X_list.append(np.zeros(window_size))
            y_list.append(0)
    else:
        # 正常训练场景
        for i in range(window_size, len(values)):
            window = values[i-window_size:i]
            X_list.append(window)
            y_list.append(values[i])
    
    X = np.array(X_list)
    y = np.array(y_list)
    return X, y